﻿using System;
using System.IO;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using WeBlog.Helpers;
using WeBlog.Interfaces;
using WeBlog.Models;
using WeBlog.Repositories;
using WeBlog.Services;

namespace WeBlog.Controllers {
	public class HomeController : ApplicationController
	{		
		private readonly IEmailService _emailService;
		
		public HomeController(IUnitOfWork unitOfWork, IEmailService emailService )
			: base( unitOfWork )
		{			
			_emailService = emailService;
		}
		
		public ActionResult Contact()
		{
			var model = new ContactViewModel();
			return View(model);
		}

		[HttpPost]        
		public ActionResult Contact(ContactViewModel contact)
		{
			if (ModelState.IsValid)
			{
				var userRepository = new UserRepository(UnitOfWork);
				var adminEmails = userRepository.FindEmailsByRole(Role.Admin);
				string subject = String.Format("{0} {1}", SiteConfiguration.ContactEmailSubjectPrefix, contact.Subject);
				_emailService.SendContactMail( contact.Email, contact.FullName, subject.Trim(), contact.Message, adminEmails);            
				TempData.SetStatusMessage(Resources.Strings.Contact_EmailSentSucessfully);
				return RedirectToRoute("Default");				
			}
			return View(contact);
		}

		public ActionResult Search(string query, GridSettings settings)
		{						
			var model = new SearchViewModel(settings, UnitOfWork);
			model.Query = query;

			return View( model );
		}

		[HttpPost]
		[WeBlogAuthorize(Role.Admin,Role.Author,Role.Editor)]
		public string Upload()
		{
			var jss = new JavaScriptSerializer();

			try {
				var files = this.HttpContext.Request.Files;
				var uploadFile = new FileInfo(files[0].FileName);
				Boolean isImage = FileManager.IsImage(uploadFile);
				DirectoryInfo uploadDir = isImage ? FileManager.ImageDirectory : FileManager.FileDirectory;
				//get a unique name for the file in case a file with that name already exists						
				FileInfo uniqueFile = FileManager.GetUniqueFile(uploadDir, uploadFile);
				//save the file to disk						
				files[0].SaveAs(uniqueFile.FullName);

				string html = isImage ? FileManager.GetImageMarkup(uniqueFile) : FileManager.GetFileMarkup(uniqueFile);

				return jss.Serialize(new JsonResponse {Success = true, Result = html});				
			}
			catch (Exception ex) {
				return jss.Serialize(new JsonResponse { Success = false, Result = "", Message = ex.Message });
			}			
		}

		public FileResult GetImage(string id)
		{		   
			var path = Path.Combine(FileManager.ImageDirectory.FullName, id);
			return new FileStreamResult(new FileStream(path, FileMode.Open), FileManager.GetContentType(path));
		}

		[OutputCache(Duration = 600, VaryByParam = "id")]
		public FileResult GetFile(string id)
		{
			var path = Path.Combine(FileManager.FileDirectory.FullName, id);
			return base.File(path, FileManager.GetContentType(path));
		}        
	}
}
